/*
 * Reply.java
 * 
 * Version information
 * 
 * Mar 30, 2006
 * 
 * Copyright (c) AmSoft Systems, 2006
 */
package net.amsoft.iservice.icontact.webapp.struts.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.amsoft.iservice.icontact.hibernate.Message;
import net.amsoft.iservice.icontact.hibernate.dataObject.LoginData;
import net.amsoft.iservice.icontact.service.IContact;
import static net.amsoft.iservice.icontact.util.IContactConstants.*;
import net.amsoft.iservice.icontact.webapp.struts.form.ReplyForm;
import net.amsoft.iservice.util.EmailService;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

/**
 * Reply action class is used to interact with the user who contacted to the
 * current i-name. The sender user can be contacted through the email or i-name
 * whatever is provided while placing the contact request.
 * 
 * @author rahul
 * 
 */
public class Reply extends BaseAction {

	public static final Logger oLogger = Logger.getLogger(Reply.class);

	public ActionForward process(ActionMapping oMapping, ActionForm oForm,
			HttpServletRequest oRequest, HttpServletResponse oResponse)
			throws Exception {
		oLogger.info("process() : entry");
		try {
			LoginData oLoginData = (LoginData) oRequest.getSession(false)
					.getAttribute(SESSION_LOGIN_OBJ);
			if (oLoginData.isLoginStatus() == false) {
				return oMapping.findForward(FWD_CHKLOGIN);
			}
			ReplyForm oReplyForm = (ReplyForm) oForm;
			oReplyForm.debug("reply");
			String sHash = oReplyForm.getHash();
			Message oParent = null;

			if (sHash != null && sHash.trim().length() > 0) {
				oLogger.debug("process() : Hash: " + sHash + ", Subject: "
						+ oReplyForm.getSubject() + ", Message: "
						+ oReplyForm.getMsg());
				oParent = IContact.saveReply(sHash, oReplyForm.getSubject(),
						oReplyForm.getMsg());
			}
			if (oParent != null) {
				oLogger.debug("process() : send reply mail");
				sendReplyMail(oRequest, oReplyForm, oParent);
			}
		} catch (Exception e) {
			// TODO set some error msg
			oLogger.error("process() : Exception: " + e.getMessage());
		}
		return oMapping.findForward(FWD_SUCCESS);
	}

	/**
	 * Used to send the reply to e-mail address of the sender.
	 * 
	 * @param oRequest
	 *            Current Http Request
	 * @param oReplyForm
	 *            Reply data
	 * @param parentMsg
	 *            Original contact request
	 */
	private void sendReplyMail(HttpServletRequest oRequest,
			ReplyForm oReplyForm, Message parentMsg) {
		oLogger.info("sendReplyMail() : entry ");
		String sReplyLink = prepareReplyLink(oRequest, parentMsg.getSynonym()
				.getName(), parentMsg.getHash());
		String sCompleteMsg = prepareReplyMsg(oRequest, parentMsg, oReplyForm
				.getMsg(), sReplyLink);

		String sFromAddr = "noreply@" + oRequest.getServerName();

		EmailService oEmailService = new EmailService();
		oEmailService.setBody(sCompleteMsg);
		oEmailService.setSubject(oReplyForm.getSubject());
		oEmailService.setFromAddress(sFromAddr);
		oEmailService.setReplyToAddress(sFromAddr);
		ArrayList<String> lRecipient = new ArrayList<String>();
		lRecipient.add(parentMsg.getSenderEMail());
		oEmailService.setReceipientList(lRecipient);
		oEmailService.sendMail();
		oLogger.info("sendReplyMail(): exit");
	}

	/**
	 * This method creates a reply link which is send to the user who initiated
	 * the communication thread. The reply link can be used to continue the
	 * further communication in the same message thread.
	 * 
	 * @param oRequest
	 *            Current Http request
	 * @param sSynonym
	 *            Name of the synonym
	 * @param sKey
	 *            Key value used to create link
	 * @return String reply link
	 */
	private String prepareReplyLink(HttpServletRequest oRequest,
			String sSynonym, String sKey) {
		oLogger.info("prepareReplyLink() : entry with data : Synonym: "
				+ sSynonym + ", Key: " + sKey);
		String sReplyLink = oRequest.getScheme() + "://"
				+ oRequest.getServerName();
		if (oRequest.getServerPort() != 80) {
			sReplyLink += ":" + oRequest.getServerPort();
		}
		try {
			sReplyLink += CONTACT_ACTION + "?" + REQ_PTR_SYN + "=" + sSynonym
					+ "&" + REQ_PTR_HASH + "="
					+ URLEncoder.encode(sKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			sReplyLink += CONTACT_ACTION + "?" + REQ_PTR_SYN + "=" + sSynonym
					+ "&" + REQ_PTR_HASH + "=" + sKey;
			oLogger.warn("prepareReplyLink() : Exception :" + e.getMessage()
					+ ", ReplyLink: " + sReplyLink);
		}
		oLogger.info("prepareReplyLink(): exit, return ReplyLink: "
				+ sReplyLink);
		return sReplyLink;
	}

	/**
	 * Used to create the text body of the message that is to be sent to the
	 * recieved email.
	 * 
	 * @param oRequest
	 *            Current Http request
	 * @param parentMsg
	 *            Original coantact request
	 * @param body
	 *            Text body of message
	 * @param sReplyLink
	 *            Reply link
	 * @return String text body of the message
	 */
	private String prepareReplyMsg(HttpServletRequest oRequest,
			Message parentMsg, String body, String sReplyLink) {
		oLogger.info("prepareReplyMsg() : entry with data : Body: " + body
				+ ", Reply Link: " + sReplyLink);
		MessageResources oResources = getResources(oRequest);
		String sCompleteMsg = oResources.getMessage(oRequest.getLocale(),
				MSG_DEF_REPLY_EMAIL_MSG, parentMsg.getSenderName(), parentMsg
						.getSynonym().getName(), body, sReplyLink);
		oLogger.info("prepareReplyMsg(): exit, return Complete Message: "
				+ sCompleteMsg);
		return sCompleteMsg;
	}
}
